<template>
  <div class="task-list">
    <div class="task-header">
      <h3>课程任务</h3>
      <el-button 
        type="primary" 
        size="small" 
        @click="showAddTaskDialog = true"
        v-if="userStore.user.id"
      >
        添加任务
      </el-button>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="tasks.length === 0" class="empty-container">
      <el-empty description="暂无课程任务" />
    </div>
    
    <div v-else class="tasks-container">
      <div 
        v-for="task in tasks" 
        :key="task.id" 
        class="task-item"
      >
        <div class="task-content">
          <h4 class="task-title">{{ task.title }}</h4>
          <p class="task-description">{{ task.body }}</p>
          <div class="task-meta">
            <span class="task-date">创建时间: {{ formatDate(task.createTime) }}</span>
            <span class="task-author">创建者ID: {{ task.userid }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加任务对话框 -->
    <el-dialog
      v-model="showAddTaskDialog"
      title="添加课程任务"
      width="600px"
    >
      <el-form
        :model="taskForm"
        :rules="taskRules"
        ref="taskFormRef"
        label-width="100px"
      >
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入任务标题" />
        </el-form-item>
        
        <el-form-item label="任务描述" prop="body">
          <el-input
            v-model="taskForm.body"
            type="textarea"
            :rows="4"
            placeholder="请输入任务描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddTaskDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAddTask" :loading="addingTask">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useUserStore } from '../stores/user'
import * as api from '../services/api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  }
})

const userStore = useUserStore()
const tasks = ref([])
const loading = ref(false)
const showAddTaskDialog = ref(false)
const addingTask = ref(false)
const taskFormRef = ref()

const taskForm = reactive({
  title: '',
  body: ''
})

const taskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' }
  ],
  body: [
    { required: true, message: '请输入任务描述', trigger: 'blur' }
  ]
}

const loadTasks = async () => {
  if (!props.courseId) return
  
  try {
    loading.value = true
    const response = await api.getTasksByCourse(props.courseId)
    tasks.value = Array.isArray(response) ? response : []
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
    tasks.value = []
  } finally {
    loading.value = false
  }
}

const handleAddTask = async () => {
  if (!taskFormRef.value) return
  
  try {
    await taskFormRef.value.validate()
    addingTask.value = true
    
    const taskData = {
      ...taskForm,
      userid: userStore.user.id,
      parentid: props.courseId,
      parentType: '课程'
    }
    
    await api.addTask(taskData)
    
    ElMessage.success('任务添加成功')
    showAddTaskDialog.value = false
    
    // 重置表单
    taskForm.title = ''
    taskForm.body = ''
    
    // 重新加载任务列表
    loadTasks()
    
  } catch (error) {
    console.error('添加任务失败:', error)
    ElMessage.error('添加任务失败')
  } finally {
    addingTask.value = false
  }
}

const formatDate = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(parseInt(timestamp))
  return date.toLocaleString('zh-CN')
}

watch(() => props.courseId, loadTasks)

onMounted(() => {
  loadTasks()
})
</script>

<style scoped>
.task-list {
  margin-top: 20px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.task-header h3 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.loading-container, .empty-container {
  padding: 40px;
  text-align: center;
}

.tasks-container {
  space-y: 16px;
}

.task-item {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 16px;
  background: white;
  transition: box-shadow 0.2s;
}

.task-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.task-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 10px 0;
}

.task-description {
  color: #606266;
  line-height: 1.6;
  margin: 0 0 15px 0;
}

.task-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>